from sklearn.neighbors import NearestNeighbors
import numpy as np
import matplotlib.pyplot as plt
# 创建一些二维数据
X = np.array([[1,1],[1,3],[2,2],[2.5,5],[3,1],[4,2],[2,3.5],[3,3],[3.5,4]])
# 构建最近邻的个数
num_neighbors = 3
# 输入数据点
input_point = [2.6,1.7]
# 画出数据点
plt.figure()
plt.scatter(X[:,0],X[:,1],marker='o',s=25,color='k')
# 构建最近邻模型
knn = NearestNeighbors(n_neighbors=num_neighbors,algorithm='ball_tree').fit(X)
# 计算输入数据点和所有数据点之间的关系
# indices记录离输入点最近的k个点的索引
distances,indices = knn.kneighbors([input_point])
print(distances)
print(indices)
for rank,index in enumerate(indices[0][:num_neighbors]):
    print(str(rank+1)+'-->',X[index])

# 画出最近邻
plt.scatter(X[indices][0][:][:,0],X[indices][0][:][:,1],marker='o',s=150,color='k',facecolors='none')
plt.scatter(input_point[0],input_point[1],marker='x',s=150,color='k')
plt.show()
print(X[indices])